/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jse.concurrent;

import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Join方法:直到所调用的线程执行完毕，才会执行当前线程   SE5的concurrent包中的CyclicBarrier类可达到类似作用，且更方便
 * Interrupt方法：中断调用的线程
 * @author WangShuai
 */
class Sleeper extends Thread {

    private int duration;

    public Sleeper(String name, int sleepTime) {
        super(name);
        duration = sleepTime;
        start();
    }

    public void run() {
        try {
            sleep(duration);
        } catch (InterruptedException e) {
            //捕获中断异常，通过isInterrupt方法标识，由于异常被捕获时将清理这个标志，所以在一场中将一直为false
            System.out.println(getName() + " was interrupted. "
                    + "isInterrupted(): " + isInterrupted());
            return;
        }
        System.out.println(getName() + " has awakened");
    }
}

class Joiner extends Thread {

    private Sleeper sleeper;

    public Joiner(String name, Sleeper sleeper) {
        super(name);
        this.sleeper = sleeper;
        start();
    }

    public void run() {
        try {
            System.out.println(sleeper.isAlive());
            sleeper.join();   //sleeper如果不在运行并不会出现异常
        } catch (InterruptedException e) {
            System.out.println("Interrupted");
        }
        System.out.println(getName() + " join completed");
    }
}

public class TestJoin {

    public static void main(String[] args) {
        Sleeper sleepy = new Sleeper("Sleepy", 1500),
                grumpy = new Sleeper("Grumpy", 1500);
        Joiner dopey = new Joiner("Dopey", sleepy),
                doc = new Joiner("Doc", grumpy);
        //grumpy.interrupt();
    }
}
